<template>
  <div class="submit-list-container">
    <!-- 筛选区域 -->
    <div class="filter-section">
      <a-select
        v-model:value="status"
        style="width: 120px"
        placeholder="状态"
        @change="onFilterChange"
      >
        <a-select-option value="">全部</a-select-option>
        <a-select-option value="ACCEPTED">通过</a-select-option>
        <a-select-option value="WRONG_ANSWER">答案错误</a-select-option>
        <a-select-option value="COMPILE_ERROR">编译错误</a-select-option>
        <a-select-option value="RUNTIME_ERROR">运行时错误</a-select-option>
        <a-select-option value="TIME_LIMIT_EXCEEDED">超时</a-select-option>
        <a-select-option value="MEMORY_LIMIT_EXCEEDED">内存超限</a-select-option>
        <a-select-option value="JUDGING">评测中</a-select-option>
      </a-select>
      <a-select
        v-model:value="language"
        style="width: 120px"
        placeholder="语言"
        @change="onFilterChange"
      >
        <a-select-option value="">全部</a-select-option>
        <a-select-option value="Java">Java</a-select-option>
        <a-select-option value="cpp">C++</a-select-option>
        <a-select-option value="python">Python</a-select-option>
      </a-select>
    </div>

    <!-- 提交列表表格 -->
    <a-table
      :columns="columns"
      :data-source="submissions"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
      row-key="runId"
    >
      <!-- 自定义列渲染 -->
      <template #bodyCell="{ column, record, text }">
        <!-- 状态列 -->
        <template v-if="column.key === 'status'">
          <a-tag :color="getStatusColor(record.status)">
            {{ getStatusText(record.status) }}
          </a-tag>
        </template>

        <!-- 题目列 -->
        <template v-else-if="column.key === 'problem'">
          <span>{{ record.problemNo }} - {{ record.problemTitle }}</span>
        </template>

        <!-- 操作列 -->
        <template v-else-if="column.key === 'action'">
          <a-button type="link" @click="handleViewDetail(record)">查看详情</a-button>
        </template>
        
        <!-- 其他列使用默认内容显示 -->
        <template v-else>
          {{ text }}
        </template>
      </template>
    </a-table>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { getUserSubmissions } from "@/api/hoj-judge.js";

export default {
  name: 'SubmitList',
  setup() {
    const router = useRouter()
    const status = ref('')
    const language = ref('')
    const loading = ref(false)
    const submissions = ref([])
    
    // 分页信息
    const paginationInfo = ref({
      current: 1,
      pageSize: 10,
      total: 0
    })

    // 计算属性：分页配置
    const pagination = computed(() => ({
      current: paginationInfo.value.current,
      pageSize: paginationInfo.value.pageSize,
      total: paginationInfo.value.total,
      showTotal: total => `共 ${total} 条记录`,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50']
    }))

    // 表格列定义
    const columns = [
      {
        title: '提交ID',
        dataIndex: 'runId',
        key: 'runId',
        width: 80
      },
      {
        title: '题目',
        key: 'problem',
        width: 200
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        width: 150,
        align: 'center'
      },
      {
        title: '语言',
        dataIndex: 'language',
        key: 'language',
        width: 100,
        align: 'center'
      },
      {
        title: '提交时间',
        dataIndex: 'createdAt',
        key: 'createdAt',
        width: 170,
        align: 'center'
      },
      {
        title: '操作',
        key: 'action',
        width: 100,
        align: 'center',
        fixed: 'right'
      }
    ]

    // 获取提交列表
    const fetchSubmissions = async () => {
      loading.value = true
      const params = {
        page: paginationInfo.value.current - 1,  // API使用0-based索引
        size: paginationInfo.value.pageSize,
      }
      
      // 只有当有值时才添加这些可选参数
      if (status.value) params.status = status.value
      if (language.value) params.language = language.value
      
      try {
        const resp = await getUserSubmissions(params);
        
        if (resp.content) {
          // 确保每条记录都有runId属性
          submissions.value = resp.content.map(item => ({
            ...item,
            // 如果没有runId，将id设为runId
            runId: item.runId || item.id
          }));
          
          paginationInfo.value = {
            current: resp.page + 1,  // 前端显示从1开始
            pageSize: resp.size,
            total: resp.totalElements
          };
          
          // 打印第一条记录，用于调试
          if (submissions.value.length > 0) {
            console.log('First record:', submissions.value[0]);
          }
        } else {
          console.warn('API响应格式不符合预期:', resp);
        }
      } catch (error) {
        console.error('获取提交记录失败:', error);
      } finally {
        loading.value = false;
      }
    }

    // 筛选变化处理
    const onFilterChange = () => {
      paginationInfo.value.current = 1
      fetchSubmissions()
    }

    // 表格变化处理
    const handleTableChange = (pag) => {
      paginationInfo.value.current = pag.current
      paginationInfo.value.pageSize = pag.pageSize
      fetchSubmissions()
    }

    // 查看详情
    const handleViewDetail = (record) => {
      router.push(`/oj/judge-submit/${record.runId}`);
    }

    // 获取状态对应的颜色
    const getStatusColor = (status) => {
      const colors = {
        'ACCEPTED': 'success',
        'WRONG_ANSWER': 'error',
        'COMPILE_ERROR': 'warning',
        'RUNTIME_ERROR': 'error',
        'TIME_LIMIT_EXCEEDED': 'warning',
        'MEMORY_LIMIT_EXCEEDED': 'warning',
        'JUDGING': 'processing',
        'SYSTEM_ERROR': 'default'
      }
      return colors[status] || 'default'
    }

    // 获取状态对应的文本
    const getStatusText = (status) => {
      const texts = {
        'ACCEPTED': '通过',
        'WRONG_ANSWER': '答案错误',
        'COMPILE_ERROR': '编译错误',
        'RUNTIME_ERROR': '运行时错误',
        'TIME_LIMIT_EXCEEDED': '超时',
        'MEMORY_LIMIT_EXCEEDED': '内存超限',
        'JUDGING': '评测中',
        'SYSTEM_ERROR': '系统错误'
      }
      return texts[status] || status
    }

    onMounted(() => {
      fetchSubmissions()
    })

    return {
      status,
      language,
      loading,
      submissions,
      columns,
      pagination,
      onFilterChange,
      handleTableChange,
      handleViewDetail,
      getStatusColor,
      getStatusText
    }
  }
}
</script>

<style scoped>
.submit-list-container {
  width: 100%;
}

.filter-section {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

@media screen and (max-width: 768px) {
  .filter-section {
    flex-wrap: wrap;
  }
}
</style> 